package com.hunk.utils;

import static com.hunk.utils.io.Print.println;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hunk.core.auth.entity.User;
import com.hunk.springMvcExercise.web.servlet.JsonRequest;

/**
 * @author Dengyx
 */
public class JacksonUtil {
	private static ObjectMapper oMapper = new ObjectMapper();

	public static <T> String getJsonStrFromBean(T t) {
		String json = "";
		try {
			json = oMapper.writeValueAsString(t);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json;
	}

	public static <T> T getBeanFromJson(String fromValue, Class<T> toValueType) {
		try {
			return oMapper.readValue(fromValue, toValueType);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static <T> T readJsonFromString(String jsonString,
			TypeReference<T> typeRef) {
		try {
			return (T)oMapper.readValue(jsonString, typeRef);
		} catch (JsonParseException e) {
			throw new RuntimeException("Deserialize from JSON failed.", e);
		} catch (JsonMappingException e) {
			throw new RuntimeException("Deserialize from JSON failed.", e);
		} catch (IOException e) {
			throw new RuntimeException("Deserialize from JSON failed.", e);
		}
	}

	/** Description:<br>
	 * 保护密码不被序列化得到
	 * @author Hunk
	 * @since 2013-4-27
	 */
	public static class Test {
		public static void main(String[] args) {
			// String result =
			// "{'methodName': 'sss', 'req':{'username':'多对多','password':'adf','realname':'阿迪飞'}}";

			JsonRequest<User> jr = new JsonRequest<User>();
			jr.setMethodName("login");
			jr.setReq(new User("user", "psd", "real"));
			//
			String result = getJsonStrFromBean(jr);
			println(result);
			String results =
						 "{\"methodName\": \"sss\", \"req\":{\"username\":\"多对多\",\"password\":\"adf\",\"realname\":\"阿迪飞\"}}";
			JsonRequest<User> jq = readJsonFromString(results, new TypeReference<JsonRequest<User>>(){});
			println(jq);
		}
	}

}
